package com.ly.demo.thread.syn;

/**
 * @author liuyang
 * @des
 * @Version 1.0
 * @Date: 22/10/2021 10:15
 */

/**
 * 线程同步：
 * 1.方法同步
 * 2.代码块同步
 */

public class ThreadSynchronization {

    class Bank {
        private int account = 10;

        public int getAccount() {
            return account;
        }

        /**
         * 同步方法
         *
         * @param money
         */
        public synchronized void saveAccount(int money) {
            account += money;
        }

        /**
         * 同步代码块
         *
         * @param money
         */
        public void saveAccount1(int money) {
            synchronized (this) {
                account += money;
            }
        }
    }

    class NewThred implements Runnable {

        private Bank bank;

        public NewThred(Bank bank) {
            this.bank = bank;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                bank.saveAccount(1);
                //                bank.seveAccount(1);
                System.out.println(Thread.currentThread().getName() + "-->第" + i + "次，账户余额：" + bank.getAccount());

            }

        }
    }

    public void useThread() {
        Bank bank = new Bank();
        NewThred newThred = new NewThred(bank);

        System.out.println("线程1：");

        Thread thread1 = new Thread(newThred);
        thread1.start();

        System.out.println("线程2：");

        Thread thread2 = new Thread(newThred);
        thread2.start();

    }

    public static void main(String[] args) {
        ThreadSynchronization threadSynchronization = new ThreadSynchronization();
        threadSynchronization.useThread();
    }

}
